package com.example.shop.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shop.persistence.entity.Goods;
import com.example.shop.persistence.entity.GoodsDetail;
import com.example.shop.persistence.mapper.GoodsDetailMapper;
import com.example.shop.persistence.mapper.GoodsMapper;
import com.example.shop.modules.sys.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author jason
 * @since 2019-12-16
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsDetailMapper goodsDetailMapper;

    /*
    根据ID查询商品详细信息
    */
    @Override
    public Goods selectGoodsInfoAll(Integer id){

        QueryWrapper<Goods> ew = new QueryWrapper<>();

        ew.eq("a.id", id);

        return goodsMapper.selectGoodsInfoAll(ew);
    }

    /*
    新增数据
    关联表新增
     */
    @Override
    public void insertGoodsAll(Goods goods, GoodsDetail goodsDetail){
        // 插入goods 表数据
        goodsMapper.insert(goods);
        // 获取 新增的goods数据ID，赋值给 goodsDetail表的goodsId字段
        goodsDetail.setGoodsId(goods.getId());
        // 将数据插入 goodsDetail 表
        goodsDetailMapper.insert(goodsDetail);
    }

    /*
    查询商品列表
     */
    @Override
    public IPage<Goods> selectGoodsList(Page<Goods> page, QueryWrapper<Goods> ew){
        return page.setRecords(goodsMapper.selectGoodsAllList(page,ew));
    }

    /*
     *   删除商品
     */
    @Override
    public void deleteGoods(String[] ids){
        goodsMapper.deleteByIds(ids);
        goodsDetailMapper.deleteByIds(ids);
    }

    /*
     *   更新商品信息
     */
    public void updateGoodsAll(Goods goods){
        //更新商品表
        goodsMapper.updateById(goods);
        // 新建商品详情表对象 并赋值
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId(goods.getId());
        goodsDetail.setDetail(goods.getDetail());
        // 更新商品详情表
        goodsDetailMapper.updateByGoodsId(goodsDetail);
    }
}
